package util

import (
	"fmt"
	"github.com/go-ego/gse"
	"kukukaki/models"
	"os"
	"os/exec"
	"path/filepath"
	"github.com/astaxie/beego"
	"strings"
)

var Seg gse.Segmenter
var sysPath string
//var dictpath string = "/app/kukukaki/dict/mydict.txt"

func GetAPPRootPath() string {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return ""
	}
	p, err := filepath.Abs(file)
	if err != nil {
		return ""
	}
	return filepath.Dir(p)
}

func init() {
	fmt.Println("--------dict path root" + GetAPPRootPath())
	//Seg.LoadDict(beego.AppConfig.String("dict"))
	Seg.LoadDict(beego.AppConfig.String("dict_cn"),beego.AppConfig.String("dict_en"),beego.AppConfig.String("dict_jp"))

}
func UpdateDict() {

	err := os.Remove(beego.AppConfig.String("dict_cn")) //删除文件test.txt
	if err != nil {
		//如果删除失败则输出 file remove Error!
		fmt.Println("file remove Error!")
		//输出错误详细信息
		fmt.Printf("%s", err)
	}

	err = os.Remove(beego.AppConfig.String("dict_en")) //删除文件test.txt
	if err != nil {
		//如果删除失败则输出 file remove Error!
		fmt.Println("file remove Error!")
		//输出错误详细信息
		fmt.Printf("%s", err)
	}
	
	err = os.Remove(beego.AppConfig.String("dict_jp")) //删除文件test.txt
	if err != nil {
		//如果删除失败则输出 file remove Error!
		fmt.Println("file remove Error!")
		//输出错误详细信息
		fmt.Printf("%s", err)
	}
	
	f, err1 := os.Create(beego.AppConfig.String("dict_cn")) //创建文件
	defer f.Close()
	if err1 == nil {
		//n2, err3 := f.Write(d1) //写入文件(字节数组)
		names, err3 := models.FindIISourceAllName()
		if err3 == nil {
			var str string = ""
			for i := range names {
				str += strings.Replace(strings.ToUpper(names[i].CN)," ", "", -1)  + " 3 n\r\n"
			}
			if len(str) > 0 {

				//fmt.Printf("写入 %d 个字节n", n2)
				n3, err2 := f.WriteString(str) //写入文件(字节数组)
				if err2 != nil {
					fmt.Printf(" write dict is err :" + err2.Error())
				} else {
					fmt.Printf("写入 %d 个字节n", n3)
				}

			}else{
				fmt.Println(" err: db is null")
			}

		} else {
			fmt.Println(" err:" + err3.Error())
		}
	}
	
	
	f, err1 = os.Create(beego.AppConfig.String("dict_en")) //创建文件
	defer f.Close()
	if err1 == nil {
		//n2, err3 := f.Write(d1) //写入文件(字节数组)
		names, err3 := models.FindIISourceAllNameEn()
		if err3 == nil {
			var str string = ""
			for i := range names {
				if names[i].EN != "" &&  names[i].EN != "#N/A" {
					//cn := strings.Replace(names[i].INCI, " ", "+", -1)
					str += strings.Replace(strings.TrimSpace(names[i].EN), " ", "+", -1) + " 3 n\r\n"
				}
				
			}
			if len(str) > 0 {

				//fmt.Printf("写入 %d 个字节n", n2)
				n3, err2 := f.WriteString(str) //写入文件(字节数组)
				if err2 != nil {
					fmt.Printf(" write dict is err :" + err2.Error())
				} else {
					fmt.Printf("写入 %d 个字节n", n3)
				}


			}else{
				fmt.Println(" err: db is null")
			}

		} else {
			fmt.Println(" err:" + err3.Error())
		}
	}



	f, err1 = os.Create(beego.AppConfig.String("dict_jp")) //创建文件
	defer f.Close()
	if err1 == nil {
		//n2, err3 := f.Write(d1) //写入文件(字节数组)
		names, err3 := models.FindIIAllNameJp()
		if err3 == nil {
			var str string = ""
			for i := range names {
				if names[i].NameJP != ""  && names[i].NameJP !=  "nodata" {
					str += names[i].NameJP + " 3 n\r\n"
				}
			}
			if len(str) > 0 {

				//fmt.Printf("写入 %d 个字节n", n2)
				n3, err2 := f.WriteString(str) //写入文件(字节数组)
				if err2 != nil {
					fmt.Printf(" write dict is err :" + err2.Error())
				} else {
					fmt.Printf("写入 %d 个字节n", n3)
				}



			}else{
				fmt.Println(" err: db is null")
			}

		} else {
			fmt.Println(" err:" + err3.Error())
		}
	}
	
	f.Sync()
	Seg.LoadDict(beego.AppConfig.String("dict_cn"),beego.AppConfig.String("dict_en"),beego.AppConfig.String("dict_jp"))
	
}
func SetSysPath(path string) {
	sysPath = path
}


func RemoveRepByLoop(slc []string,lang *string) []string {
    result := []string{}  // 存放结果
    for i := range slc{
        flag := true
        for j := range result{
            if slc[i] == result[j] ||  slc[i]=="" || (*lang == "cn" && len(slc[i]) < 4)  {
                flag = false  // 存在重复元素，标识为false
                break
            }
        }
        
        if flag {  // 标识为false，不添加进结果
	        if *lang == "en" {
	        	//英文换+
	        	result = append(result, strings.Replace(slc[i], "+", " ", -1))
	        }else if *lang == "cn" {
	        	result = append(result,strings.ToUpper(slc[i]))
	        }else{
	        	result = append(result, slc[i])
	        }
            
        }
    }
    return result
}
 

func GetIngredients(str *string,lang *string) []string {
	//text := []byte(str)

	sl := Seg.Slice([]byte(*str), false)

	//去掉空字符 和 重复
	sl = RemoveRepByLoop(sl,lang)
	
	//中文去掉空或1个子
	//for index := 0; index < len(sl); index++ {
		//fmt.Println(len(sl[index]))
		//fmt.Println(sl[index])
	//	if len(sl[index]) < 4 {
	//		sl = append(sl[:index], sl[index+1:]...)
	//		index--
	//	}

	//}
	
	
	
	/*
	for index := 0; index < len(sl); index++ {
		sl[index] = "^"+sl[index]+"$"
	}
*/
	return sl
}
